package com.whnk.pm.util;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;

import com.whnk.common.pm.constants.EmpConstants;
import com.whnk.pm.dto.Duration;

public class DateUtil {

    public static String durationOverlap(Date startDate, Date endDate, List<Duration> list, String operationType) {
        list.sort(Comparator.comparing(Duration::getStartDate));
        list.sort(Comparator.comparing(t -> t.getEndDate() == null? new Date() : t.getEndDate()));
        if (CollectionUtils.isNotEmpty(list)) {
            Date workEndDate = list.get(list.size() - 1).getEndDate();
            if (workEndDate == null) {
                workEndDate = new Date();
            }
            if (startDate.after(workEndDate) || startDate.compareTo(workEndDate) == 0) {
                return EmpConstants.EMP_DATE_NOT_OVERFLAP;
            } else if (endDate.before(list.get(0).getStartDate()) || endDate.compareTo(list.get(0).getStartDate()) == 0) {
                return EmpConstants.EMP_DATE_NOT_OVERFLAP;
            } else {
                int index = 0;
                for (int i = 0; i < list.size(); i++) {
                    Duration eduInfo = list.get(i);
                    if (endDate.before(eduInfo.getStartDate()) || endDate.compareTo(eduInfo.getStartDate()) == 0) {
                        index = i;
                        break;
                    }
                }
                if (index != 0) {
                    Date beforeDate = list.get(index - 1).getEndDate() == null ? new Date() : list.get(index - 1).getEndDate();
                    if (startDate.after(beforeDate) || beforeDate.compareTo(startDate) == 0) {
                        return EmpConstants.EMP_DATE_NOT_OVERFLAP;
                    }
                }
            }
        } else {
            return EmpConstants.EMP_DATE_NOT_OVERFLAP;
        }
        return EmpConstants.EMP_DATE_OVERFLAP;
    }
}
